<?php

class Emms_Form_Loan_Calculator extends HTech_Form
{
    private $_loanProductParams;
    private $_maxFirstPaymentDate;  
    
    private function _setLoanProductParams()
    {
        if($this->_request->isPost()) {
            $products = new LoanProducts();
            try {
                $this->_loanProductParams = $products->getRecord((int) $this->_request->getParam('LoanProductId'))->d;
            } catch (Exception $e) {
                $e = $e;
            }
        }
    }
    
    private function _setMaxFirstPaymentDate()
    {
        if($this->_request->isPost()) {
            try {
                $this->_maxFirstPaymentDate = Emms_PmtPlan::getMaxFirstPaymentDate(
                    $this->_request->getPost('DeliveryDate'), $this->_loanProductParams['PrincipalGraceMargin'], $this->_loanProductParams['PaymentFrequency']);
            } catch (Exception $e) {
                $e = $e; 
            }
        }
    }
        
    public function __construct() 
    {
        parent::__construct(); 
        $this->_setLoanProductParams();
        $this->_setMaxFirstPaymentDate();
        
        $this->setName('Calculator');
        
        $this->setAttrib('title', $this->translate("Financial calculator"));
        $this->setDescription($this->translate("Loan products"));
                                                
        $loanProductId = new Zend_Form_Element_Select('LoanProductId');
        $loanProductId->setLabel("Loan product")                
            ->setAttrib('size','6')
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addMultiOptions($this->_db->fetchPairs('select LoanProductId, Name from loan_products')); 
        
        $deliveryDate = new Zend_Form_Element_Text('DeliveryDate');
        $deliveryDate->setLabel("Delivery date")
            ->setRequired(true)
            ->addPrefixPath('HTech_Validate', 'HTech/Validate', 'validate')
            ->addValidator('Date', true, array(
                'weekday' => true, 
                'maxDate' => $this->_request->getPost('FirstPaymentDate'),
                'messages' => array(
                    'msgWeekday' => $this->translate("Weekend dates not allowed"),
                    'msgMaxDateStrict' => $this->translate("Non valid date or date range"))));
        
        $firstPaymentDate = new Zend_Form_Element_Text('FirstPaymentDate');
        $firstPaymentDate->setLabel("First payment date")
            ->setRequired(true)
            ->addPrefixPath('HTech_Validate', 'HTech/Validate', 'validate')
            ->addValidator('Date', true, array(
                'weekday' => true, 
                'minDate' => $this->_request->getParam('DeliveryDate'),
                'messages' => array(
                    'msgWeekday' => $this->translate("Weekend dates not allowed"),
                    'msgMinDateStrict' => $this->translate("Non valid date or date range"))))
            ->addValidator('Callback', true, array(
                'callback' => array($this, 'checkGraceMarginCallback'),
                'messages' => $this->translate(sprintf("Principal grace margin invalid or exceeded. Maximum allowed: %s", $this->_maxFirstPaymentDate))));       
        
        $kp = new Zend_Form_Element_Text('Principal');
        $kp->setLabel("Principal")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Required field, can't be empty")))
            ->addValidator('Regex', true, array(
                'pattern' => '(^\d+(\.\d{2})?$)',
                'messages' => $this->translate("Invalid amount")));
        
        $interestCalculation = new Zend_Form_Element_Text('InterestCalculation');
        $interestCalculation->setLabel("Interest calculation")
            ->setRequired(true)
            ->setAttrib('readonly', 'true'); 
                                
        $paymentFrequency = new Zend_Form_Element_Text('PaymentFrequency');
        $paymentFrequency->setLabel("Payment frequency")
            ->setRequired(true)
            ->setAttrib('readonly', 'true');  
                                
        $calendarType = new Zend_Form_Element_Text('CalendarType');
        $calendarType->setLabel("Calendar type") 
            ->setRequired(true)
            ->setAttrib('readonly', 'true'); 
                       
        $installments = new Zend_Form_Element_Text('Installments');
        $installments->setLabel("Installments")
            ->setRequired(true)
            ->setAttrib('readonly', 'true'); 
                                
        $annualPercentageRate = new Zend_Form_Element_Text('AnnualPercentageRate');
        $annualPercentageRate->setLabel("Annual pct. rate")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Annual pct. rate can't be empty")))
            ->addValidator('Float', true, array('messages' => $this->translate("Invalid Std. annual pct. rate")))
            ->addValidator('Between', true, array(
                'min' => $this->_loanProductParams['AnnualPercentageRateMin'],
                'max' => $this->_loanProductParams['AnnualPercentageRateMax'],
                'inclusive' => true,
                'messages' => sprintf($this->translate("Valid range from %s to %s"), 
                        $this->_loanProductParams['AnnualPercentageRateMin'], 
                        $this->_loanProductParams['AnnualPercentageRateMax'])));
                                
        $loanInsurancePct = new Zend_Form_Element_Text('LoanInsurancePct');
        $loanInsurancePct->setLabel("Loan ins. pct.")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Loan ins. pct. can't be empty")))
            ->addValidator('Regex', true, array(
                'pattern' => '(^\d+(\.\d{2})?$)',
                'messages' => $this->translate("Invalid Std. loan ins. pct.")))
            ->addValidator('Between', true, array(
                'min' => $this->_loanProductParams['LoanInsurancePctMin'],
                'max' => $this->_loanProductParams['LoanInsurancePctMax'],
                'inclusive' => true,
                'messages' => sprintf($this->translate("Valid range from %s to %s"), 
                        $this->_loanProductParams['LoanInsurancePctMin'], 
                        $this->_loanProductParams['LoanInsurancePctMax'])));
                                
        $healthInsurancePct = new Zend_Form_Element_Text('HealthInsurancePct');
        $healthInsurancePct->setLabel("Health ins. pct.")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Health ins. pct. can't be empty")))
            ->addValidator('Regex', true, array(
                'pattern' => '(^\d+(\.\d{2})?$)',
                'messages' => $this->translate("Invalid Std. health ins. pct.")))
            ->addValidator('Between', true, array(
                'min' => $this->_loanProductParams['HealthInsurancePctMin'],
                'max' => $this->_loanProductParams['HealthInsurancePctMax'],
                'inclusive' => true,
                'messages' => sprintf($this->translate("Valid range from %s to %s"), 
                        $this->_loanProductParams['HealthInsurancePctMin'], 
                        $this->_loanProductParams['HealthInsurancePctMax'])));
                                
        $administrativeFeePct = new Zend_Form_Element_Text('AdministrativeFeePct');
        $administrativeFeePct->setLabel("Admin. fee pct.")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Admin. fee pct. can't be empty")))
            ->addValidator('Regex', true, array(
                'pattern' => '(^\d+(\.\d{2})?$)',
                'messages' => $this->translate("Invalid Std. admin. fee pct.")))
            ->addValidator('Between', true, array(
                'min' => $this->_loanProductParams['AdministrativeFeePctMin'],
                'max' => $this->_loanProductParams['AdministrativeFeePctMax'],
                'inclusive' => true,
                'messages' => sprintf($this->translate("Valid range from %s to %s"), 
                        $this->_loanProductParams['AdministrativeFeePctMin'], 
                        $this->_loanProductParams['AdministrativeFeePctMax'])));
                                
        $principalGraceRate = new Zend_Form_Element_Text('PrincipalGraceRate');
        $principalGraceRate->setLabel("Principal grace rate")
            ->setRequired(true)
            ->addValidator('NotEmpty', true, array('messages' => $this->translate("Principal grace rate can't be empty")))
            ->addValidator('Regex', true, array(
                'pattern' => '(^\d+(\.\d{2})?$)',
                'messages' => $this->translate("Invalid Std. principal grace rate")))
            ->addValidator('Between', true, array(
                'min' => $this->_loanProductParams['PrincipalGraceRateMin'],
                'max' => $this->_loanProductParams['PrincipalGraceRateMax'],
                'inclusive' => true,
                'messages' => sprintf($this->translate("Valid range from %s to %s"), 
                        $this->_loanProductParams['PrincipalGraceRateMin'], 
                        $this->_loanProductParams['PrincipalGraceRateMax'])));
        
        $submit = new Zend_Form_Element_Submit('Submit');
        $submit->setLabel("Submit")
            ->addDecorator(new HTech_Form_Decorator_Button(array('type' => 'submit')));   
        
        $name = new Zend_Form_Element_Hidden('Name');
        $principalGraceMargin = new Zend_Form_Element_Hidden('PrincipalGraceMargin');
        $delayGrace = new Zend_Form_Element_Hidden('DelayGrace');
        $delayPenaltyRate = new Zend_Form_Element_Hidden('DelayPenaltyRate');
        $delayPenaltyFixedCharge = new Zend_Form_Element_Hidden('DelayPenaltyFixedCharge');
        
        $this->addElements(array($loanProductId, $interestCalculation, $calendarType, $paymentFrequency, $installments, 
            $annualPercentageRate, $loanInsurancePct, $healthInsurancePct, $administrativeFeePct, $principalGraceRate, 
            $deliveryDate, $firstPaymentDate, $kp, $submit, $principalGraceMargin, $delayGrace, $delayPenaltyRate, $delayPenaltyFixedCharge, $name));
    }
    
    public function checkGraceMarginCallback($date)
    {
        if($date > $this->_maxFirstPaymentDate) return false;
        return true;
    }  
    
    /**
     * Returns false if $date is hollidays, malformed or invalid. Return true otherwise.
     * 
     * @param type $date Format YYYY-MM-DD
     * @return boolean
     */
    public function checkHollidaysCallback($date)
    {
        try {
            $hollidays = Emms_Date::isHollidays($date);
        } catch (Exception $e) {
            $e = $e;
            $hollidays = true;
        }
        if($hollidays) return false;
        return true; 
    }  
}